package com.tiantianyuegou.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.Tools;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by ivany on 2016/1/15.
 * 安全验证
 */
public class SettingSafeCodeActivity extends BaseActivity implements TextWatcher, View.OnClickListener {


    private EditText mEt_phone, mEt_code;
    private Button mBtn_getVerify, mBtn_sure;

    private LoadingDialog mLodingDialog;
    private String mTvCode;
    private TimeCount time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settingsafecode);
      Tools.changeSystemBar(this);
        setTitle("设置安全验证手机");
        initViews();
    }

    @Override
    public void findViewByIds() {
        mEt_phone = (EditText) findViewById(R.id.edt_phone);
        mEt_code = (EditText) findViewById(R.id.edt_getcode);
        mBtn_getVerify = (Button) findViewById(R.id.btn_getcode);
        mBtn_sure = (Button) findViewById(R.id.btn_sure);
    }

    @Override
    public void initListener() {
        mEt_code.addTextChangedListener(this);
        mEt_phone.addTextChangedListener(this);
        mBtn_getVerify.setOnClickListener(this);
        mBtn_sure.setOnClickListener(this);
    }


    @Override
    public void initData() {
        time = new TimeCount(this, 60000, 1000);
        mLodingDialog = new LoadingDialog(this);
        String phone = SPHelper.getTmPhone();
        StringBuffer phoneShow = new StringBuffer();
        if (phone != null && phone.length() == 11) {
            phoneShow.append(phone.substring(0, 3));
            phoneShow.append("****");
            phoneShow.append(phone.substring(7));
            mEt_phone.setText(phoneShow.toString());
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String code = mEt_code.getText().toString();
        if (code != null && !"".equals(code)) {
            mBtn_sure.setEnabled(true);
            mBtn_sure.setAlpha(1.0f);
        } else {
            mBtn_sure.setAlpha(0.5f);
            mBtn_sure.setEnabled(false);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_getcode:
                mLodingDialog.show();
                mLodingDialog.setMsg("正在获取验证");
                getVerifyCode();
                break;
            case R.id.btn_sure:
                String code = mEt_code.getText().toString();
                if (mTvCode == null) {
                    showMsg("请先获取验证码");
                } else {
                    if (code != null) {
                        if (code.equals(mTvCode)) {
                            mLodingDialog.show();
                            mLodingDialog.setMsg("正在设置支付密码");
                            setBalance();
                        } else {
                            showMsg("验证码错误，请重新输入");
                        }
                    } else {
                        showMsg("请输入验证码");
                    }
                }

                break;
        }
    }

    //设置验证码
    private void setBalance() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        params.addBodyParameter("payPassword", getIntent().getStringExtra("password"));
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.SET_PAY_PASS, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLodingDialog.dismiss();
                Log.e("TAG", "setBalance response:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("设置支付密码失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            Intent intent = new Intent();
                            setResult(Constant.SETTING_SAFECODE_RESULT, intent);
                            finish();
                        }
                        String msg = root.getString("message");
                        showMsg(msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mLodingDialog.dismiss();
                        showMsg("解析异常");
                    }

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLodingDialog.dismiss();
                Log.e("TAG", "request failure :" + s);
                showMsg("当前网络不可用，请检查您的网设置");
            }
        });
    }

    //获取验证码
    private void getVerifyCode() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("phone", SPHelper.getTmPhone());
        params.addBodyParameter("type", "2");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GET_CODE, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("TAG", "getVerfiyCode response :" + responseInfo.result);
                mLodingDialog.dismiss();
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("获取验证码失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            time.start();
                            String result = root.getString("result");
                            mTvCode = result;
                        }
                        String msg = root.getString("message");
                        showMsg(msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("解析失败");
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLodingDialog.dismiss();
                Log.e("TAG", "request failure :" + s);
                showMsg("当前网络不可用，请检查您的网设置");
            }
        });
    }

    /**
     * 时间计时类
     */
    class TimeCount extends CountDownTimer {
        Activity activity;

        public TimeCount(Activity activity, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            this.activity = activity;
        }

        /**
         * 计时过程
         *
         * @param millisUntilFinished
         */
        @SuppressLint("NewApi")
        @Override
        public void onTick(long millisUntilFinished) {
            mBtn_getVerify.setClickable(false);
            mBtn_getVerify.setBackground(activity.getResources().getDrawable(R.drawable.btn_getcode_timecount_bg));
            mBtn_getVerify.setTextColor(getResources().getColor(R.color.textcolor_3));
            mBtn_getVerify.setText(millisUntilFinished / 1000 + "S后重发");
        }

        /**
         * 计时完毕时触发
         */
        @SuppressLint("NewApi")
        @Override
        public void onFinish() {
            mBtn_getVerify.setText(R.string.register_get_code);
            mBtn_getVerify.setClickable(true);
            mBtn_getVerify.setBackground(activity.getResources().getDrawable(R.drawable.btn_getcode_bg));
            mBtn_getVerify.setTextColor(getResources().getColor(R.color.bg_button_normal));

        }
    }
}
